﻿using Aop.Api.Util;
using HUGY.BLL;
using HUGY.Common;
using HUGY.Core.Base;
using HUGY.Model;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public partial class Notify_url : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        Dictionary<string, string> sArray = GetRequestPost();
        if (sArray.Count != 0)
        {
            bool flag = AlipaySignature.RSACheckV1(sArray, config.alipay_public_key, config.charset, config.sign_type, false);
            if (flag)
            {
                string trade_status = Request.Form["trade_status"];
                if (trade_status == "TRADE_SUCCESS")
                {
                    string body = Request.Form["body"];
                    string total_amount = Request.Form["total_amount"];
                    string out_trade_no = Request.Form["out_trade_no"];
                    if (body.Split(',')[0].ToString() == "bzj")
                    {
                        DataTable member = GetList(" SP_MEMBER ", " TB_BZJ_PRICE ", " TB_NUMBER='" + body.Split(',')[1] + "' ");
                        decimal bzjall = Convert.ToDecimal(total_amount) + Convert.ToDecimal(member.Rows[0]["TB_BZJ_PRICE"]);
                        string bondId = "";
                        DataTable dt = GetList(" SELECT * FROM SP_BONDMANAGE ORDER BY TB_BZJ_PRICE ");
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (bzjall >= Convert.ToDecimal(dt.Rows[i]["TB_BZJ_PRICE"]))
                            {
                                bondId = dt.Rows[i]["ID"].ToString();
                            }
                            else
                            {
                                break;
                            }
                        }
                        Update("SP_MEMBER", "TB_BZJ_STATE=1,TB_BZJ_PRICE='" + bzjall + "',TB_BZJ_BONDID='" + bondId + "'", " TB_NUMBER='" + body.Split(',')[1] + "' ");
                        string bzjId = Guid.NewGuid().ToString();
                        string bzjFkId = body.Split(',')[1];
                        string bzjPrice = total_amount;
                        int bzjState = 0;
                        DateTime bzjDate = DateTime.Now;
                        Insert("SP_BZJ_PRICE", "'" + bzjId + "','" + bzjFkId + "','" + bzjPrice + "','" + bzjState + "','" + bzjDate + "'");
                    }
                    else
                    {
                        DataTable order = GetList(" SP_ORDER ", " FK_ID,TB_ADDTIME ", " ID='" + body.Split(',')[0] + "' ");
                        DataTable goods = GetList(" SP_GOODS ", " ID,TB_GOODS_PRICE ", " ID ='" + order.Rows[0]["FK_ID"] + "'");
                        string orderID = Guid.NewGuid().ToString();
                        string orderFK_ID = goods.Rows[0]["ID"].ToString();
                        string orderTB_NUMBER = out_trade_no;
                        string orderTB_PRICE = Convert.ToDecimal(total_amount).ToString("f2");
                        string orderTB_BUYER = body.Split(',')[1];
                        string orderTB_SELLER = body.Split(',')[1];
                        int orderTB_ORDER_STATE = 3;
                        int orderTB_GOODS_STATE = 3;
                        bool orderTB_ISCOMPLAINT = false;
                        string orderTB_FILE_PATH = "";
                        string orderdjs = "";
                        DateTime orderTB_ADDTIME = DateTime.Now;
                        Insert("SP_ORDER", "'" + orderID + "','" + orderFK_ID + "','" + orderTB_NUMBER + "','" + orderTB_PRICE + "','" + orderTB_BUYER + "','" + orderTB_SELLER + "','" + orderTB_ORDER_STATE + "','" + orderTB_GOODS_STATE + "','" + orderTB_ISCOMPLAINT + "','" + orderTB_FILE_PATH + "','" + orderdjs + "','" + orderTB_ADDTIME + "'");
                        if (DateTime.Now.ToString("yyyy-MM-dd") == Convert.ToDateTime(order.Rows[0]["TB_ADDTIME"]).ToString("yyyy-MM-dd"))
                        {
                            SpCopyGoods copy = new SpCopyGoods();
                            copy.ID = Guid.NewGuid().ToString();
                            copy.FK_ID = order.Rows[0]["FK_ID"].ToString();
                            copy.TB_ADDTIME = DateTime.Now.ToString("yyyy-MM-dd");
                            Insert("SP_COPY_GOODS", "'" + copy.ID + "','" + copy.FK_ID + "','" + copy.TB_ADDTIME + "'");
                        } 
                        DataTable addprice = GetList(" SP_DEPLOY ", " TB_DEPLOY_NUM ", " TB_DEPLOY_ID='addPrice' ");
                        double pri = Convert.ToDouble(goods.Rows[0]["TB_GOODS_PRICE"].ToString()) * Convert.ToDouble(addprice.Rows[0]["TB_DEPLOY_NUM"].ToString());
                        string goodsTB_GOODS_PRICE = Convert.ToDecimal((Convert.ToDouble(goods.Rows[0]["TB_GOODS_PRICE"].ToString()) + pri).ToString()).ToString();
                        string goodsTB_GOODS_DATE = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                        Update("SP_GOODS", "TB_ISWTDM=3,TB_GOODS_PRICE='" + goodsTB_GOODS_PRICE + "',TB_GOODS_DATE='" + goodsTB_GOODS_DATE + "'", " ID ='" + order.Rows[0]["FK_ID"] + "' ");
                        Update("SP_ORDER", "TB_GOODS_STATE=4", " ID='" + body.Split(',')[0] + "' ");
                    }
                    Response.Write("success");
                }
            }
            else
            {
                Response.Write("fail");
            }
        }
    }

    public Dictionary<string, string> GetRequestPost()
    {
        int i = 0;
        Dictionary<string, string> sArray = new Dictionary<string, string>();
        NameValueCollection coll;
        //coll = Request.Form;
        coll = Request.Form;
        String[] requestItem = coll.AllKeys;
        for (i = 0; i < requestItem.Length; i++)
        {
            sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
        }
        return sArray;

    }

    public class config
    {
        public config()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        // 应用ID,您的APPID
        public static string app_id = "2021001175636149";
        //public static string app_id = "2016102300747987";

        // 支付宝网关
        public static string gatewayUrl = "https://openapi.alipay.com/gateway.do";
        //public static string gatewayUrl = "https://openapi.alipaydev.com/gateway.do";


        // 商户私钥，您的原始格式RSA私钥
        public static string private_key = "MIIEpAIBAAKCAQEApQNr72v0ZcQwoe29kEpRlZn8/QyBErt9wJKnSeU+gbcky26N7yghecb4ArCDfqGvZMQXx9OOiY5m8BCL917az1FdoG7NZEQG8YmYNZVLlQUMW6V5YZe3rv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aTGtouB+/WEwn3cp3u+lDxl1TMxoMFQN63pJFfDlkCgYEAvgZWfa3R1mp/aKdOJBRslZYSKHE6gMUrezVXs/QqAzm+AzW5TuhE4DIfY0hUICfZny/ct9PFAoO+2U4bD9aaYw8EVOC1aEXvyoUE7Cc7jEEEdTj7qR5HXC9X31FvNJFwvvdgBYy9xYqTjq25IMknTtu5baYUgZBWvxREQUx+lZ0CgYEAtD+Yc/KQkr0dfhM2Bc2YZ4MOaFHCT3hPr5IDiar7oUDz0vJuw0H/mPTcGZXDrA7AtR1v3rncvE8vQxvKBpG1BTVr/7Nv3VvAQLp4b2w5VFz53t0L24PE1w2thb0BDoqKBRPs8t/RVN550MBAMIGYrlr7f6pOHhYOQHM2k4odqwsCgYBE1wryUMwZ/07U3Pdj/rovnsRJPmvRRpyv7+0r1iJ6NKrvgsD1IxQAnGfekc9YLteZ4b72IZPXi17SXodTP42CoWgST62obt2l4nacDsJ11wAEb3ZMGBoF/Wi6EEhXJPFRXVC98fS14bP/FlRg2j6RROxyGp6HKYEji/YGKe4ZyQKBgDfqCnbdZi++7qkveHCwaHij1RJTWn2giseh+er42XoaVgi4H9f+XzWpr6VYKgzzvp/wc8WZznmz7qtYsYD8LjVhbxExLqByV988eSPHZLlg5jpWQ9litOspWQzFptBF9a7BkZ1+BMfZA9zX5pGlgiGEI8Rkpjr7CIzBsMpv6+glAoGAGDTX8HgPLVMrT4gXieMwOpC1cGPiQhlDOBNOd7caDTQu3IX8Hd2vGVUskJbiQAHvAEq2g+Ngj+SMh2GnyOpLBCy19YxtcHyPHYAe9coxFwlJsE52ezsWAM4A06YwRShl8iUr/ogiNgpcXqFL3OiEUc4M3727rI4+ObnsckswzTg=";

        // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
        public static string alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp+IneWwL7xGsbA3eMgIv8UFN+5xgMSdo2GL8AQttAcCIUT1sEU8c72WEOfYlWT+3cVXEdJPZJUe2L/uP5fTo3LJ09NdLYIcyPbNuln5KTxKozkmDcJm2ZKe25UhsLy8u+mz1t/MIyO/V6be+PVF1j+T6f0HLntKLyUqs4xNpNYow+i3X4KIO1UPutEXnZoEAfQNXiwXIr3I82gN505BuoxhCvgW9I0sBiso0uKZ5mlShpSGaXME+iA/mDebjdza58tefzAADJJ1iN799SIcW+dtr2Mc7Z/MX9fNjfiZPpt1iLwdae4QCiaTnnR2li6RGPq0IwLbJw3BjI61iSV+hywIDAQAB";
        // public static string alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmP4mMFQnvqOcnt2si64gZVgDSR6SUBtaAA6NVxH+rV4CAYSx+exa4R0yPoZGeKscAvJu3WcmLeIoReW7eF1mlZCHD0YRI1KhIvK/tfLrJqZpIaAp+D3Py3zdqQkLck51wVp+HS3wEOJfC8akDvGOfSL/WCUVeRiSAj+2QusRYyuqDTEtsfwq3aB+tlfe+W00yAOl+MDfeGNYmpfx8deRisjJieWLJJmdnPBaf3nAtOtD7texmpkDh/XyGj4CZ9eQqRy3jqoklINRl3u4yb+NGj9XJAg4pGmBzGXi2wqiyqtlDxv0hml1Vh14zNI8IcQeE/f7ve0yl9tOQEEd0fP8VQIDAQAB";

        // 签名方式
        public static string sign_type = "RSA2";

        // 编码格式
        public static string charset = "UTF-8";

        public static string return_url = "http://www.bairuihuayuan.com/Manage/alipay/Return_url.aspx";

    }


    /// <summary>
    /// 数据库连接字符串
    /// </summary>
    private string connection = "data source=172.21.0.12;database=TB_SHOPPING;uid=admin;pwd=adminxrhy2020";

    /// <summary>
    /// 数据库命令执行方法(SQL语句)
    /// </summary>
    private int Command(string sql)
    {
        SqlConnection conn = new SqlConnection(connection);
        try
        {
            SqlCommand command = new SqlCommand(sql, conn);
            conn.Open();
            return command.ExecuteNonQuery();
        }
        catch
        {
            return 0;
        }
        finally
        {
            conn.Close();
        }
    }

    /// <summary>
    /// 查询(SQL语句)
    /// </summary>
    private DataTable GetList(string sql)
    {
        SqlConnection conn = new SqlConnection(connection);
        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
            DataTable data = new DataTable();
            adapter.Fill(data);
            return data;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    /// <summary>
    /// 完全查询(表名, 字段) //表名和字段最好加上中括号[Id]
    /// </summary>
    public DataTable GetList(string tableName, string field)
    {
        string sql = string.Format("SELECT {0} FROM {1}", field, tableName);
        return GetList(sql);
    }

    /// <summary>
    /// 条件查询(表名, 字段, 条件)
    /// </summary>
    public DataTable GetList(string tableName, string field, string where)
    {
        string sql = string.Format("SELECT {0} FROM {1} WHERE {2}", field, tableName, where);
        return GetList(sql);
    }

    /// <summary>
    /// 条件删除(表名, 条件) //返回受影响的行数, 0 表示失败
    /// </summary>
    public int Delete(string tableName, string where)
    {
        string sql = string.Format("DELETE FROM {0} WHERE {1}", tableName, where);
        return Command(sql);
    }

    /// <summary>
    /// 条件修改(表名, 更新的数据, 条件)
    /// </summary>
    public int Update(string tableName, string updateData, string where)
    {
        string sql = string.Format("UPDATE {0} SET {1} WHERE {2}", tableName, updateData, where);
        return Command(sql);
    }
    /// <summary>
    /// 条件修改(表名, 更新的数据, 条件)
    /// </summary>
    public int Insert(string tableName, string Data)
    {
        string sql = string.Format("INSERT INTO {0} VALUES({1})", tableName, Data);
        return Command(sql);
    }

}